﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MaxLeaf.Common;
using System.Data.SqlClient;
using MaxLeaf.DB;
using System.Data;


namespace MaxLeaf.DAL.K2K
{
    public class t_BarCodeDAL : BaseDAL
    {
        /// <summary>
        /// 类别
        /// </summary>
        public t_BarCodeDAL()
            : base()
        {
            strTableName = "t_BarCode";
            strUpdateFNumberTableName = "t_BarCode";
            strMapKeyFieldName = "FID";

            strDestRealKeyFieldName = string.Empty;

            mblnNeedEditKeyValue = false;

            strFieldNames = "FItemID,FBillID,FIndex,FCodeType,FBarCode,FUnitID,FTypeID";

            strFItemClassID = null;

            mblnIsIdentity = true;
        }

        protected override void Update_Before(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, DataRow drOrgData, DataRow drData)
        {
        }

        public override int Update(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strKeyValue)
        {
            KeyValuePair<string, IDataParameter[]> kvp = dbOrgK3Con.CreateCondParam(new Dictionary<string, object>() { { "fid", strKeyValue } });
            DataRow drOrg = dbOrgK3Con.GetDataFirstRow(string.Format("select fitemid from t_BarCode where {0}", kvp.Key), kvp.Value);
            if (drOrg == null) throw new MaxLeafException(string.Format("t_BarCode not exist  {0}", strKeyValue));
            dictOtherKeyFieldsCond = new Dictionary<string, object>() { { "fitemid", drOrg["fitemid"] } };
            dictDestOtherKeyFieldsCond = new Dictionary<string, object>() { { "fitemid", new ImInvMasterDAL().GetDestMapKeyValue(dbOrgK3Con, dbDestK3Con, CvtFunc.ToString(drOrg["fitemid"])) } };

            int iDestKey = base.Update(dbOrgK3Con, dbDestK3Con, strKeyValue);


            return iDestKey;
        }



        protected override void DAL_GetFieldData(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strFieldName, DataRow drOrgData, DataRow drDestData)
        {
            if (strFieldName.Equals("FitemID", StringComparison.InvariantCultureIgnoreCase))
            {
                if (CvtFunc.ToString(drDestData[strFieldName]).Length == 0)
                {
                    drDestData[strFieldName] = CvtFunc.ToString(new ImInvMasterDAL().GetDestMapKeyValue(dbOrgK3Con, dbDestK3Con, CvtFunc.ToString(drOrgData["FitemID"])));
                }

            }
            else if (strFieldName.Equals("FBillID", StringComparison.InvariantCultureIgnoreCase))
            {

                if (CvtFunc.ToString(drDestData[strFieldName]).Length == 0)
                {
                    drDestData[strFieldName] = GetFBillID(dbOrgK3Con, dbDestK3Con, drOrgData, drDestData);
                }


            }
            else if (strFieldName.Equals("FIndex", StringComparison.InvariantCultureIgnoreCase))
            {
                if (CvtFunc.ToInt(drDestData[strFieldName]) == 0)
                {
                    drDestData[strFieldName] = GetFIndex(dbOrgK3Con, dbDestK3Con, drOrgData, drDestData);
                }
            }
            else if (strFieldName.Equals("FCodeType", StringComparison.InvariantCultureIgnoreCase))
            {
                if (CvtFunc.ToInt(drDestData["FID"]) == 0)
                {
                    drDestData[strFieldName] = GetFCodeType(dbOrgK3Con, dbDestK3Con, drOrgData, drDestData);
                }
            }
            else if (strFieldName.Equals("FBarCode", StringComparison.InvariantCultureIgnoreCase))
            {

                drDestData[strFieldName] = drOrgData["FBarCode"];

            }
            else if (strFieldName.Equals("FUnitID", StringComparison.InvariantCultureIgnoreCase))
            {

                string strFUnitGroupID = GetFUnitGroupID(dbOrgK3Con, dbDestK3Con
                    , dbOrgK3Con.GetValue("select FUnitGroupID from t_MeasureUnit where FMeasureUnitID=@FMeasureUnitID", new SqlParameter[] { new SqlParameter("@FMeasureUnitID", drOrgData[strFieldName]) }));
                if (strFUnitGroupID.Length == 0)
                {
                    strFUnitGroupID = "0";
                }
                //单位
                string strOrgFUnitID = CvtFunc.ToString(drOrgData[strFieldName]);
                string strFUnitID = string.Empty;

                strFUnitID = GetFUnitID(dbOrgK3Con, dbDestK3Con, strOrgFUnitID, strFUnitGroupID);
                


                if (strFUnitID.Length == 0)
                {
                    drDestData[strFieldName] = "0";
                }
                else
                {
                    drDestData[strFieldName] = strFUnitID;
                }

            }
            else if (strFieldName.Equals("FTypeID", StringComparison.InvariantCultureIgnoreCase))
            {

                drDestData[strFieldName] = 4;

            }
            else
            {
                drDestData[strFieldName] = 0;
            }            
        }

 
        protected override DataTable DAL_GetData(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, int intdataType, object objParam)
        {
            GetDataType dataType = (GetDataType)intdataType;

            if (dataType == GetDataType.OrgData)
            {
                return Gett_BarCode(dbOrgK3Con, CvtFunc.ToString(objParam));
            }


            return base.DAL_GetData(dbOrgK3Con, dbDestK3Con, intdataType, objParam);
        }


        private string GetFUnitGroupID(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgFUnitGroupID)
        {
            t_UnitGroupDAL dal = new t_UnitGroupDAL();
            return dal.GetFUnitGroupID(dbOrgK3Con, dbDestK3Con, strOrgFUnitGroupID);

        }

        private string GetFUnitID(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgFUnitID, string strFParentID)
        {
            t_MeasureUnitDAL dal = new t_MeasureUnitDAL();
            return dal.GetFMeasureUnitID(dbOrgK3Con, dbDestK3Con, strOrgFUnitID, strFParentID);
        }

        private string GetFCodeType(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, DataRow drOrgData, DataRow drDestData)
        {
            string strSql = "select FCodeType from t_barcode where  FBillID=@FBillID and FCodeType=0";
            if (dbDestK3Con.GetDataFirstRow(strSql
                    , dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { { "FBillID", drDestData["FBillID"] } }).Value
                ) != null)
            {
                return "1";
            }
            return "0";
        }

        private string GetFIndex(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, DataRow drOrgData, DataRow drDestData)
        {
            string strSql = "select max(FIndex) from t_barcode where  FBillID=@FBillID";
            int iMax = CvtFunc.ToInt(dbDestK3Con.GetValue(strSql
                    , dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { { "FBillID", drDestData["FBillID"] } }).Value
                )) + 1;

            return CvtFunc.ToString(iMax);
        }

        private string GetFBillID(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, DataRow drOrgData, DataRow drDestData)
        {
            string strFBillID = dbDestK3Con.GetValue("select top 1 FBillID from t_barcode where fitemid=@fitemid"
                , new SqlParameter[] { new SqlParameter("@fitemid", drDestData["fitemid"]) });

            if (strFBillID.Length > 0) return strFBillID;

            string strSql = @"DECLARE @TmpID INT 
                DECLARE @fprojectval varchar(80) 
                select  @fprojectval='' 
                SET @TmpID = (SELECT FID FROM t_BillCodeRule WITH(READUNCOMMITTED) WHERE fbilltypeid='1014003' and fprojectid=3)
                update t_billcoderule set fprojectval = fprojectval+1,@fprojectval=isnull(fprojectval,1),flength=case when (flength-len(fprojectval)) >= 0 then flength else len(fprojectval) end where FID = @TmpID 
                Update ICBillNo Set FCurNo = @fprojectval where fbillid = 1014003";
            dbDestK3Con.ExecuteSql(strSql);

            strSql = "select FCurNo from ICBillNo  where fbillid = 1014003";
            string strFCurNo = dbDestK3Con.GetValue(strSql);

            strSql = "update ICBillNo Set FDesc = @FDesc Where FBillID = '1014003'";
            dbDestK3Con.ExecuteSql(strSql, new SqlParameter[] { new SqlParameter("@FDesc", BaseFunctions.FormatWithZero(CvtFunc.ToString(CvtFunc.ToInt(strFCurNo) + 1), 8)) });

            strSql = "exec GetICMaxNum 't_BarCodeHeader',@p2 output";
            SqlParameter p2 = new SqlParameter("@p2", SqlDbType.Int);
            p2.Direction = ParameterDirection.Output;
            dbDestK3Con.ExecuteSql(strSql, new SqlParameter[] { p2 });

            if (CvtFunc.ToInt(p2.Value) <= 0)
            {
                throw new MaxLeafException(string.Format("GetICMaxNum {0}", p2.Value));
            }
            strFBillID = CvtFunc.ToString(p2.Value);

            BaseFunctions.FormatWithZero(strFCurNo, 8);

            strSql = @"insert into t_barcodeheader(FBillID,fclasstypeid,FbillNo) values(@FBillID,@fclasstypeid,@FbillNo)";
            dbDestK3Con.ExecuteSql(strSql, new SqlParameter[] { 
                new SqlParameter("@FBillID", strFBillID) 
                ,new SqlParameter("@fclasstypeid", "1014003") 
                ,new SqlParameter("@FbillNo", BaseFunctions.FormatWithZero(strFCurNo, 8)) 
            });

            return strFBillID;

        }


        private DataTable Gett_BarCode(DBAccess dbOrgK3Con, string strFID)
        {
            DataTable dtt_BarCode = null;
            if (dtt_BarCode == null)
            {
                dtt_BarCode = dbOrgK3Con.GetTableData("t_BarCode", new Dictionary<string, object> { { "FID", strFID } });

            }
            return dtt_BarCode;
        }

    }
}